package com.CampusForum.community.controller;

import com.CampusForum.community.config.KaptchaConfig;
import com.CampusForum.community.entity.User;
import com.CampusForum.community.service.UserService;
import com.CampusForum.community.util.CommunityConstant;
import com.google.code.kaptcha.Producer;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.ServletResponse;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.RenderedImage;
import java.io.IOException;
import java.util.Map;

@Controller
@Slf4j
public class LoginController implements CommunityConstant {
    @Autowired
    private UserService userService;


    @Autowired
    private Producer kaptchaProducer;

    @Value("${server.servlet.context-path}")
    private String contextPath;

    /**
     * 返回注册页面
     *
     * @return
     */
    @GetMapping("/register")
    public String getRegisterHtml() {
        return "/site/register";
    }

    /**
     * 返回登录页面
     *
     * @return
     */
    @GetMapping("/login")
    public String getLoginHtml() {
        return "/site/login";
    }

    /**
     * 注册账号
     *
     * @param model
     * @param user
     * @return
     */
    @PostMapping("/register")
    public String register(Model model, User user) {
        Map<String, Object> map = userService.register(user);
        if (map == null || map.isEmpty()) {
            // 注册成功, map不为空, 返回operate-result.html页面, 提示激活
            // msg信息, 提示激活成功
            // target链接(/index), 返回主页
            model.addAttribute("msg", "请注意接收邮箱信息, 进行账号激活");
            model.addAttribute("target", "/index");
            return "/site/operate-result";
        } else {
            // 注册失败, map为空, 返回到register页面, 返回错误信息
            // 返回注册页面register
            // 返回错误信息
            // usernameMsg passwordMsg emailMsg
            model.addAttribute("usernameMsg", map.get("usernameMsg"));
            model.addAttribute("passwordMsg", map.get("passwordMsg"));
            model.addAttribute("emailMsg", map.get("emailMsg"));
        }

        return "/site/register";
    }

    /**
     * 激活用户
     */
    @GetMapping("/activation/{userId}/{activationCode}")
    public String activateUser(Model model,
                               @PathVariable("userId") int userId,
                               @PathVariable("activationCode") String activationCode) {
        // 返回状态码
        int status = userService.activateUser(userId, activationCode);
        if (status == ACTIVATION_SUCCESS) {
            // 成功激活
            model.addAttribute("msg", "激活成功,您的账号已经可以正常使用了!");
            model.addAttribute("target", "/login");
        } else if (status == ACTIVATION_REPEAT) {
            // 重复激活
            model.addAttribute("msg", "无效操作,该账号已经激活过了!");
            model.addAttribute("target", "/index");
        } else {
            //失败激活
            model.addAttribute("msg", "激活失败,您提供的激活码不正确!");
            model.addAttribute("target", "/index");
        }

        return "/site/operate-result";
    }

    /**
     * 获取验证码, 返回相应, 带有图片, session存储验证码信息
     */
    @GetMapping("/kaptcha")
    public void getKaptcha(HttpServletResponse response, HttpSession session) {
        String text = kaptchaProducer.createText();
        RenderedImage image = kaptchaProducer.createImage(text);
        session.setAttribute("kaptcha", text);
        // 将图片输出给浏览器
        response.setContentType("image/png");
        try {
            ServletOutputStream outputStream = response.getOutputStream();
            ImageIO.write(image, "png", outputStream);
        } catch (IOException e) {
            log.error("验证码生成错误: " + e.getMessage());
        }
    }

    /**
     * 登录
     * @param code 验证码
     * @param rememberme 记住我 用来判断是否持久化保存
     */
    @PostMapping("/login")
    public String login(String username, String password, String code,
                      boolean rememberme, HttpSession session,
                        Model model, HttpServletResponse response) {
        // 成功返回到重新主页 redirect:/index
        // 失败返回登录页面, 返回错误信息
        // session获取验证码, 进行判断
        // 验证码问题
        String kaptch = (String) session.getAttribute("kaptcha");
        if(StringUtils.isBlank(kaptch)||StringUtils.isBlank(code)
                ||!kaptch.equalsIgnoreCase(code)) {
            model.addAttribute("codeMsg", "验证码输入错误");
            return "/site/login";
        }
        // 账号密码处理
        Map<String, Object> map = userService.login(username, password, rememberme);
        if(map.get("ticket") != null) {
            Cookie cookie = new Cookie("ticket", (String) map.get("ticket"));
            cookie.setPath(contextPath);
            int expired = (int) map.get("time");
            cookie.setMaxAge(expired);
            response.addCookie(cookie);
            return "redirect:/index";
        } else {
            model.addAttribute("usernameMsg", map.get("usernameMsg"));
            model.addAttribute("passwordMsg", map.get("passwordMsg"));
        }
        return "/site/login";
    }
    @GetMapping("/logout")
    public String logout(@CookieValue("ticket") String ticket) {
        userService.logout(ticket);
        return "redirect:/index";
    }
}
